<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Requests\GoodsAttrRequest;
use App\Http\Controllers\Controller;
use DB,Input;

class GoodsAttrController extends Controller
{
    /**
     * 添加商品属性
     * @param \App\Http\Requests\GoodsAttrRequest $request
     * @return type
     */
    public function store(GoodsAttrRequest $request){
        $data = $request->except('_token');
        $res = DB::table('goods_attr')->insert($data);
        if(false !== $res){
            return back();
        } else {
            return back()->with(['errors'=>'添加失败']);
        }
    }
    
    /**
     * 执行修改属性
     * @return type
     */
    public function update()
    {
        $request = new GoodsAttrRequest();
        
        $data  = Input::except('_token');
        $errors = $request->validateInput($data)->all();
        
        if($errors){
            $info = '';
            foreach($errors as $value){
                $info .= $value . "\n";
            }
            return response()->json(['status'=>0, 'info'=>$info]);
        }
        
        // 执行修改
        $res = DB::table('goods_attr')->where('id', $data['id'])->update($data);
        if(false !== $res){
            return response()->json(['status'=>1, 'info'=>'修改成功']);
        } else {
            return response()->json(['status'=>0, 'info'=>'修改失败']);
        }
    }
    
    /**
     * 删除属性
     * @param type $id
     * @return type
     */
    public function destroy($id)
    {
        $goods_id = DB::table('goods_attr')->where('id', $id)->pluck('goodd_id');
        $num = DB::table('goods_attr')->where('goods_id', $goods_id)->count();
        if($num <= 1){
            return response()->json(['status'=>0, 'info'=>'商品至少要有一个属性']);
        }
        
        $res = DB::table('goods_attr')->where('id', $id)->delete();
        if(false !== $res){
            return response()->json(['status'=>1, 'info'=>'删除成功']);
        } else {
            return response()->json(['status'=>0, 'info'=>'删除失败']);
        }
    }
}